<!-- source get frames -->
<template>
    <el-card>
        <Table :data="tableData" :column="tableTitle" :operation="true" :page="page" :loading="loading"
            @onSizeChange="onSizeChange" @onCurrentChange="onCurrentChange" @setCellColor="setCellColor">
            <template #search>
                <div><el-button type="primary" @click="onAddJob">添加工作</el-button></div>
                <div><el-input v-model="searchForm.jobName" placeholder="请输入工作名称"></el-input></div>
                <div><el-button @click="onRefresh" icon="RefreshRight" circle></el-button></div>
                <div><el-button @click="onSearch" type="primary" icon="Search">查询</el-button></div>
            </template>
            <template #column="scope">
                <el-button @click="onEdit(scope)" type="text" style="color:var(--edit)">编辑</el-button>
                <el-button @click="onDelete(scope)" type="text" style="color:var(--delete)">删除</el-button>
                <el-button @click="onStart(scope)" type="text" style="color:var(--start)">运行</el-button>
                <el-button @click="onLog(scope)" type="text" style="color:var(--log)">开启日志</el-button>
            </template>
        </Table>

        <el-dialog :title="jobTitle" v-model="jobVisible" :show-close="false">
            <el-form :model="jobForm" :rules="rules" status-icon label-width="100px"
                style="padding-top: 20px; padding-bottom: 20px;">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item prop="jobName" label="任务名称" :rules="[
                            { required: true, message: '请输入任务名称', trigger: 'blur' },]">
                            <el-input v-if="operate == 0" v-model="jobForm.jobName" placeholder="请输入任务名称"></el-input>
                            <el-input v-if="operate == 1" v-model="jobForm.jobName" placeholder="请输入任务名称"></el-input>
                            <el-input v-if="operate == 2" disabled v-model="jobForm.jobName"
                                placeholder="请输入任务名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item prop="fps" label="提取帧率" :rules="[
                            { required: true, message: '请输入提取帧率', trigger: 'blur' },]">

                            <el-select v-if="operate == 2" disabled v-model="jobForm.fps" placeholder="请选择提取帧率">
                                <el-option v-for="fpsOption in [24, 30, 60]" :key="fpsOption" :label="fpsOption"
                                    :value="fpsOption"></el-option>
                            </el-select>
                            <el-select v-else v-model="jobForm.fps" placeholder="请选择提取帧率">
                                <el-option v-for="fpsOption in [24, 30, 60]" :key="fpsOption" :label="fpsOption"
                                    :value="fpsOption"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item prop="outputExt" label="输出图片格式" :rules="[
                            { required: true, message: '请输入提取帧率', trigger: 'blur' },]">
                            <el-select v-if="operate == 2" disabled v-model="jobForm.outputExt" placeholder="请选择输出图片格式">
                                <el-option label="JPG" value="jpg"></el-option>
                                <el-option label="PNG" value="png"></el-option>
                            </el-select>
                            <el-select v-else v-model="jobForm.outputExt" placeholder="请选择输出图片格式">
                                <el-option label="JPG" value="jpg"></el-option>
                                <el-option label="PNG" value="png"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="jobVisible = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>

    <!-- 其他代码省略 -->
    <el-card>
        <h2>实时日志:</h2>
        <div class="log-container">
            <div v-for="(log, index) in logMessages" :key="index">{{ log }}</div>
        </div>
        <el-button type="primary" @click="onClearLogs">清空日志</el-button>
    </el-card>

    <el-dialog v-model="logDialogVisible" title="实时日志" width="70%">
        <div class="log-container">
            <div v-for="(log, index) in logMessages" :key="index">{{ log }}</div>
        </div>
        <template #footer>
            <el-button @click="logDialogVisible = false">最小化页面</el-button>
            <el-button type="primary" @click="closeWebSocket">停止日志接收</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { reactive, toRefs, onMounted } from 'vue';
import { saveFaceJob, updateFaceJob, FaceJobPage, FaceJobPagePlus, delFaceJob, startJob } from '../../api/systemApi.js'
import Table from '../../components/Table.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useJobGroupStore } from '../../store/settings';


let webSocket = null;

const jobGroupStore = useJobGroupStore();
const currentGroupId = jobGroupStore.getJobGroupId;

const state = reactive({
    searchForm: {
        jobName: '',
    },
    loading: false,
    page: {
        pageNum: 1,
        pageSize: 10,
        total: 1,
    },
    tableTitle: [
        { prop: '', label: '', fixed: 'left' },
        { prop: 'jobId', label: 'id' },
        { prop: 'jobName', label: '名称' },
        { prop: 'jobGroupId', label: '作业组' },
        { prop: 'fps', label: '提取帧率' },
        { prop: 'outputExt', label: '输出格式' },
        { prop: 'jobGroupId', label: '作业组' },
        { prop: 'jobInputDir', label: '作业目录' },
        { prop: 'createBy', label: '创建人' },
        { prop: 'createTime', label: '创建时间' }
    ],
    tableData: [],
    jobVisible: false,
    jobTitle: "添加工作",
    operate: 0,
    jobBasicForm: {
        jobGroupId: currentGroupId,
        jobSort: 1,
        command: 'step1_extract_images_from_video_data_src.bat'
    },
    jobForm: {
        jobId: '',
        jobName: '',
        fps: '',
        outputExt: '',
    },
    logMessages: [],
    logDialogVisible: false

});

// 从响应式状态中提取引用以在模板中使用
const { searchForm, loading, page, tableTitle, tableData, jobGroupId, jobVisible, jobTitle,
    operate, jobForm, jobBasicForm, logMessages, logDialogVisible } = toRefs(state);

onMounted(() => {
    onJobPage();
})

const onLog = (scope) => {
    const jobId = scope.column.row.jobId;
    initWebSocket(jobId); // 使用 jobId 初始化 WebSocket
    logDialogVisible.value = true; // 显示日志对话框
};

const handleLogMessage = (message) => {
    // 将新消息添加到日志数组中
    logMessages.value.push(message);
};

const initWebSocket = (jobId) => {
    const wsUrl = "ws://123.57.18.66:8080/websocket"; // 您的 WebSocket URL
    if (!webSocket || webSocket.readyState !== WebSocket.OPEN) {
        webSocket = new WebSocket(wsUrl);

        webSocket.onopen = () => {
            console.log("WebSocket connection opened");
            webSocket.send(`subscribe:${jobId}`); // 订阅特定的 jobId
        };

        webSocket.onmessage = (event) => {
            console.log("Received message:", event.data);
            // 在这里处理接收到的消息，例如更新日志显示
            handleLogMessage(event.data);
        };

        webSocket.onerror = (error) => {
            console.error("WebSocket error:", error);
            ElMessage.error('WebSocket 连接发生错误');
        };

        webSocket.onclose = () => {
            console.log("WebSocket connection closed");
            // 可以在这里尝试重新连接
            ElMessage.warning('WebSocket 连接已关闭');
        };
    } else {
        webSocket.send(`subscribe:${jobId}`); // 如果 WebSocket 已经打开，则直接发送订阅请求
    }
};

const closeWebSocket = () => {
    if (webSocket && webSocket.readyState === WebSocket.OPEN) {
        webSocket.close();  // 关闭 WebSocket 连接
        ElMessage.warning('WebSocket 连接已关闭');
    }
};

const onClearLogs = () => {
    logMessages.value = []; // 清空当前日志
};

// 初始化数据
const onJobPage = () => {
    state.loading = true;
    var temp = Object.assign(state.searchForm, state.page)
    FaceJobPagePlus(Object.assign(state.jobBasicForm, temp)).then(res => {
        state.loading = false;
        state.tableData = res.rows;
        state.page.total = res.total;
    })
}

const onSizeChange = (e) => {
    state.page.pageSize = e;
    onJobPage();
}
const onCurrentChange = (e) => {
    state.page.pageNum = e;
    onJobPage();
}
const onRefresh = () => {
    state.searchForm = {
        jobName: null,
    }
    onJobPage()
}

const onSearch = () => {
    onJobPage()
}


// 添加作业组
const onAddJob = () => {
    state.jobTitle = "添加工作";
    state.operate = 0;
    state.jobForm = {
        jobId: '',
        jobName: '',
        fps: '',
        outputExt: ''
    }
    state.jobVisible = true;
}

// 编辑
const onEdit = (val) => {
    state.jobTitle = "修改工作";
    state.operate = 1;
    state.jobForm = {
        jobId: val.column.row.jobId,
        jobName: val.column.row.jobName,
        fps: val.column.row.fps,
        outputExt: val.column.row.outputExt
    }
    state.jobVisible = true;
}

const onStart = (val) => {
    state.jobTitle = "运行工作";
    state.operate = 2;

    state.jobForm = {
        jobId: val.column.row.jobId,
        jobName: val.column.row.jobName,
        fps: val.column.row.fps,
        outputExt: val.column.row.outputExt
    }
    state.jobVisible = true;
}


// 删除
const onDelete = (val) => {
    ElMessageBox.confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let param = val.column.row.jobId
        delFaceJob(param).then(res => {
            if (res) {
                ElMessage.success('删除成功!');
            }
        })
    }).catch(e => {
        console.log(e)
    })
}

// 提交任务的方法
// const onSubmit = async () => {
//     const jobData = {
//         ...jobForm.value, // 展开jobForm对象里的所有属性
//     };

//     // 创建URLSearchParams对象
//     const params = new URLSearchParams();
//     Object.keys(jobData).forEach(key => {
//         if (jobData[key] !== null && jobData[key] !== undefined) {
//             params.append(key, jobData[key]);
//         }
//     });

//     saveFaceJobGroup(params).then(res => {
//         console.log("任务组提交成功", res);
//         if (res.data && res.code === 200 && res.data.faceJobGroupId) {
//             const jobStore = useJobStore();
//             jobStore.setJobGroupId(res.data.faceJobGroupId);
//             console.log("id", jobStore.getJobGroupId)
//         }
//     }).catch(err => {
//         console.error("任务组提交失败", err);
//     });
// };

const onSubmit = async () => {
    if (state.operate == 0) {
        saveFaceJob(
            Object.assign(state.jobBasicForm, state.jobForm)
        ).then(res => {
            if (res) {
                ElMessage.success({
                    message: '添加成功！',
                    type: 'success'
                });
                state.jobVisible = false;
            }
        });
    } else if (state.operate == 1) {
        updateFaceJob(Object.assign(state.jobBasicForm, state.jobForm)).then(res => {
            if (res) {
                ElMessage.success({
                    message: '修改成功！',
                    type: 'success'
                });
                state.jobVisible = false;
            }
        });
    } else {
        startJob(Object.assign(state.jobForm)).then(res => {
            if (res && res.code == 200) {
                ElMessage.success({
                    message: '成功发送运行指令',
                    type: 'success'
                });
                state.jobVisible = false;
            } else {
                ElMessage.error({
                    message: res.message,
                    type: 'error'
                });
            }
        });
        state.jobVisible = false;
    }
};

const setCellColor = (e, callback) => {
    /**
     * e.row：表格那一行的数据
     * e.column：表格单元格那一列的信息
     */
    if (e.row.delFlag === 0 && e.column.property === 'delFlagName') {
        callback({ color: '#67C23A', fontWeight: '700' });
    } else if (e.row.delFlag === 1 && e.column.property === 'delFlagName') {
        callback({ color: '#f00', fontWeight: '700' });
    } else {
        callback({});
    }
}



</script>

<style lang="scss" scoped>

.log-container {
    max-height: 500px;
    overflow-y: auto;
    background: #f0f8ff; /* 浅蓝色背景 */
    border: 2px solid #1e90ff; /* 深蓝色边框 */
    padding: 10px;
    font-size: 16px; /* 字体大小 */
    font-family: 'Courier New', monospace; /* 等宽字体 */
    line-height: 1.6;
    color: #2f4f4f; /* 深绿灰色字体 */
    text-shadow: 1px 1px 2px #5f6163; /* 文字阴影 */
    border-radius: 10px; /* 边框圆角 */
}
</style>
